#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
'''
@File    :   role.py
@Time    :   2023/11/16 16:50:49
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
from typing import List
from django.shortcuts import get_object_or_404
from ninja import Router, Schema, ModelSchema, Field, Query
from ninja.pagination import paginate
from system.models import Role
from utils.ninja import MyPagination
from utils.crud import retrieve

  
router = Router()


class Filters(Schema):
  id: str = Field(None)
  name: str = Field(None)

  
class RoleSchemaIn(Schema):
  name: str
  code: str
  status: bool = True

  
class RoleScemaOut(ModelSchema):
  class Config:
    model = Role
    model_fields = "__all__"


  
@router.get("/role", response=List[RoleScemaOut])
@paginate(MyPagination)
def role(request, filter: Filters = Query(...)):
  query_set = retrieve(request=request, model=Role, filters=filter)
  return query_set

  
  
@router.post("/role", response=RoleScemaOut)
def create_role(request, data: RoleSchemaIn):
  if not isinstance(data, dict):
    data = data.dict()
  query = Role.objects.create(**data)
  return query

  
@router.put("/role/{id}", response=RoleScemaOut)
def update_role(request, id: int, data: RoleSchemaIn):
  instance = get_object_or_404(Role, id=id)
  data_dict = data.dict()
  for attr, value in data_dict.items():
    setattr(instance, attr, value)
  instance.save()
  return instance

  
@router.delete("/role/{id}")
def delete_role(request, id: int):
  instance = get_object_or_404(Role, id=id)
  instance.delete()
  return {"success": True}